import fs from "fs";
import path from "path";
import archiver from "archiver";

init();

async function init() {
    await deleteZip();
    zipDirectory();
}

function deleteZip() {
    return new Promise(resolve => {
        fs.unlink("dist.zip", err => {
            if (err) {
                console.error(err);
                resolve(false);
            } else {
                console.log("delete dist.zip");
                resolve(true);
            }
        });
    });
}

function zipDirectory() {
    const output = fs.createWriteStream("dist.zip");
    const archive = archiver("zip", {
        zlib: { level: 9 }
    });

    output.on("close", function () {
        console.log(archive.pointer() + " total bytes");
        console.log("Archiver has been finalized and the output file dist.zip has been created");
    });

    archive.on("warning", function (err) {
        if (err.code === "ENOENT") {
            console.warn("Stat warning");
        } else {
            throw err;
        }
    });

    archive.on("error", function (err) {
        throw err;
    });

    archive.pipe(output);
    archive.directory("dist", false);
    archive.finalize();
}

